package com.bw.controller;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bw.domain.SysUser;
import com.bw.service.SysUserService;
import com.bw.utils.common.JWTUtils;
import com.bw.utils.common.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

@RestController
@RequestMapping("/auth")
public class AuthController {
    @Autowired
    SysUserService sysUserService;
    @Resource
    AuthenticationManager authenticationManager;
    @RequestMapping("/login")
    public Result login(@RequestBody SysUser sysUser){

        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(sysUser.getUname(), sysUser.getPwd() + salt);
        authenticationManager.authenticate(usernamePasswordAuthenticationToken);
//        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(SysUser::getUname,sysUser.getUname());
//        SysUser one = sysUserService.getOne(queryWrapper);
//        if(one==null){
//            return Result.fail("用户名不存在");
//        }
//        //用户输入的密码加盐加密
//        String s = DigestUtil.md5Hex(sysUser.getPwd() + salt);
//        if(!s.equals(one.getPwd())){
//            return Result.fail("密码不存在");
//        }
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getUname,sysUser.getUname());
        SysUser one = sysUserService.getOne(queryWrapper);

        //存token
        String token = JWTUtils.createToken(one.getId()+"", 12 * 60);
        System.out.println("token-----------"+token);
        return Result.success(token);
    }
    public static final String salt="nihao";
    @Resource
    PasswordEncoder passwordEncoder;
    @PostConstruct
    public String initPwd(){
        String str="123";
//        String s = DigestUtil.md5Hex(str + salt);
        String encode = passwordEncoder.encode(str + salt);
        System.out.println("初始化密码==============="+encode);
        return encode;
    }

}
